import { Strategy, IStrategyOptions } from 'passport-local';
import { PassportStrategy } from '@nestjs/passport';
import { HttpException, HttpStatus, Injectable } from '@nestjs/common';
import { UserDocument } from 'src/models/user';
import { compareSync } from 'bcryptjs';
import { InjectModel } from '@nestjs/mongoose';
import { Model } from 'mongoose';

@Injectable()
export class LocalStrategy extends PassportStrategy(Strategy, 'local-admin') {
  constructor(
    @InjectModel('User')
    private readonly authService: Model<UserDocument>,
  ) {
    super({
      usernameField: 'username',
      passwordField: 'password',
    } as IStrategyOptions);
  }

  async validate(username: string, password: string): Promise<any> {
    const user = await this.authService
      .findOne({ username })
      .select('+password');
    if (!user) {
      throw new HttpException(
        { status: 403, message: '用户名或密码不正确' },
        HttpStatus.FORBIDDEN,
      );
    }
    if (!compareSync(password, user.password)) {
      throw new HttpException(
        { status: 403, message: '用户名或密码不正确' },
        HttpStatus.FORBIDDEN,
      );
    }
    return user;
  }
}
